<template>
  <div class="teacher-timetable">
    <h2>教师课表</h2>
    <div class="timetable-wrapper" v-loading="loading">
      <table class="timetable">
        <thead>
          <tr>
            <th>时间</th>
            <th v-for="d in weekdays" :key="d.value">{{ d.label }}</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="sec in sections" :key="sec">
            <td class="sec-col">第{{ sec }}节</td>
            <td v-for="d in weekdays" :key="d.value" class="slot">
              <template v-if="grid && grid[d.value] && grid[d.value][sec] && grid[d.value][sec].length">
                <div class="course-cell" v-for="c in grid[d.value][sec]" :key="c.id || c._uid">
                  <strong>{{ c.name || c.courseName }}</strong>
                  <div class="minor">{{ (c.teacherName || teacherName || '') + (c.location ? ' ' + c.location : '') }}</div>
                </div>
              </template>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>
<script>
import { getTeacherTimetable } from '@/api'
export default {
  name:'TeacherTimetable',
  data() { return { loading:false, courses:[], grid:{}, teacherName:'',
    weekdays:[{value:1,label:'周一'},{value:2,label:'周二'},{value:3,label:'周三'},{value:4,label:'周四'},{value:5,label:'周五'},{value:6,label:'周六'},{value:7,label:'周日'}],
    sections:[1,2,3,4,5,6,7,8,9,10]
  }},
  async created() {
    const info = this.$store.state.user.userInfo || JSON.parse(localStorage.getItem('userInfo')||'{}')
    this.teacherName = info.username || info.name || ''
    this.fetchCourses()
  },
  methods:{
    async fetchCourses(){
      this.loading = true
      try {
        const res = await getTeacherTimetable()
        this.courses = res.data || []
        if (process.env.NODE_ENV !== 'production') {
          console.debug('[TeacherTimetable][raw]', this.courses)
        }
        this.buildGrid()
        if (!this.courses.length) {
          this.$message.info('暂无课程数据')
        }
      } catch(e){ console.error('[TeacherTimetable] fetch error', e); this.$message.error('加载课表失败') } finally { this.loading=false }
    },
    buildGrid(){
      const g = {}
      let fallbackIdx = 0

      const weekdayCharMap = { '一':1,'二':2,'三':3,'四':4,'五':5,'六':6,'日':7,'天':7 }

      const toInt = v => {
        const n = parseInt(v,10)
        return Number.isNaN(n)?undefined:n
      }

      const pushCourse = (weekday, secs, course) => {
        if (!g[weekday]) g[weekday] = {}
        for (const s of secs) {
          if (s < 1 || s > 20) continue // 简单防御
            if (!g[weekday][s]) g[weekday][s] = []
          g[weekday][s].push(course)
        }
      }

      for (const course of this.courses) {
        let weekday
        let sections = []

        // A. 直接型字段
        if (Number.isInteger(course.weekday) && course.weekday>=1 && course.weekday<=7) {
          weekday = course.weekday
        }

        // B. section / sectionStart/End / sectionCount / length / duration
        if (weekday) {
          if (Array.isArray(course.sections) && course.sections.length) {
            sections = course.sections.filter(s => Number.isInteger(s))
          } else if (Number.isInteger(course.section)) {
            // 如果还有 sectionCount/length/duration 表示连续节次
            const len = toInt(course.sectionCount) || toInt(course.length) || toInt(course.duration)
            if (len && len>1) {
              for (let i=0;i<len;i++) sections.push(course.section + i)
            } else {
              sections = [course.section]
            }
          } else if (Number.isInteger(course.sectionStart) && Number.isInteger(course.sectionEnd) && course.sectionStart <= course.sectionEnd) {
            for (let i=course.sectionStart;i<=course.sectionEnd;i++) sections.push(i)
          }
        }

        // C. 解析 time / classTime / courseTime 等字符串
        if (!weekday || !sections.length) {
            const timeStr = course.time || course.classTime || course.courseTime || ''
          if (timeStr) {
            // 支持：星期三第1~4节 / 星期三第1-4节 / 周三 1-4节 / 周三第1到4节 / 周三第1至4节 / 周三第3节
            const pattern = /[星期周]([一二三四五六日天])[^\d]*?(?:第)?(\d+)(?:\s*[~\-－—到至](\d+))?\s*节?/;
            const m = timeStr.match(pattern)
            if (m) {
              weekday = weekday || weekdayCharMap[m[1]]
              const start = toInt(m[2])
              const end = toInt(m[3]) || start
              if (start) {
                for (let i=start;i<=end;i++) sections.push(i)
              }
            }
            // 纯数字简写：例如 "1-1-3" => 周1 第1~3节；"1-1-1" => 周1 第1节
            if ((!weekday || !sections.length) && /\d/.test(timeStr)) {
              const compact = timeStr.trim().replace(/\s+/g,'')
              let mNum = compact.match(/^([1-7])[~\-]([0-9]{1,2})[~\-]([0-9]{1,2})$/)
                if (mNum) {
                  weekday = weekday || parseInt(mNum[1],10)
                  let s = parseInt(mNum[2],10)
                  let third = parseInt(mNum[3],10)
                  // 兼容两种语义：
                  // 1) weekday-start-end  (原逻辑) 例: 3-3-6 => 第3~6节
                  // 2) weekday-start-count (新需求) 例: 3-3-4 => 从第3节起共4节 => 3,4,5,6
                  // 采用启发式判断：
                  //   如果 (third - s + 1) < third  且  (课程对象存在 sectionCount/length/duration 等于 third) 或 明显出现“count”语义，则视为 count
                  //   否则：视为 end
                  let useCount = false
                  const declaredLen = toInt(course.sectionCount) || toInt(course.length) || toInt(course.duration)
                  if (declaredLen && declaredLen === third && (third - s + 1) !== third) {
                    useCount = true
                  } else if ((third - s + 1) < third) { // 例如 3-3-4 若当作 end 只占 2 节 (< 4) 更可能是 count
                    useCount = true
                  }
                  if (useCount) {
                    const end = s + third - 1
                    if (process.env.NODE_ENV !== 'production') {
                      console.debug('[TeacherTimetable][parse numeric count]', compact, '=> start', s, 'count', third, 'end', end)
                    }
                    for (let i=s;i<=end;i++) sections.push(i)
                  } else {
                    let e = third
                    if (e < s) { const t = s; s = e; e = t }
                    for (let i=s;i<=e;i++) sections.push(i)
                  }
              } else {
                mNum = compact.match(/^([1-7])[~\-]([0-9]{1,2})$/)
                if (mNum) {
                  weekday = weekday || parseInt(mNum[1],10)
                  sections.push(parseInt(mNum[2],10))
                }
              }
            }
          }
        }

        // D. 如果仍没有 weekday，用回退
        if (!weekday) {
          weekday = (fallbackIdx % 5) + 1
          fallbackIdx++
        }

        // E. 没有解析出节次，再看是否有 duration / sectionCount 搭配一个 start-like 字段
        if (!sections.length) {
          const startCand = toInt(course.section) || toInt(course.sectionStart) || 1
          const len = toInt(course.sectionCount) || toInt(course.length) || toInt(course.duration) || 1
          for (let i=0;i<len;i++) sections.push(startCand + i)
        }

        // 去重排序
        sections = Array.from(new Set(sections)).sort((a,b)=>a-b)
        pushCourse(weekday, sections, course)
      }

      this.grid = g
      if (process.env.NODE_ENV !== 'production') {
        console.debug('[TeacherTimetable][grid]', this.grid)
      }
      // 若解析后 grid 完全为空但原始 courses 有值，提示可能字段不匹配
      if (this.courses.length && Object.keys(this.grid).length === 0) {
        this.$message.warning('课程数据已获取，但时间/节次字段未识别，请检查后端字段')
      }
    }
  }
}
</script>
<style scoped>
.teacher-timetable { padding:16px; height:100%; box-sizing:border-box; }
.timetable-wrapper { overflow:auto; background:#fff; padding:12px; border-radius:8px; box-shadow:0 1px 4px rgba(0,0,0,.08); height:calc(100vh - 160px); }
.timetable { width:100%; border-collapse:collapse; min-width:800px; table-layout:fixed; height:100%; }
.timetable th, .timetable td { border:1px solid #e5e6eb; padding:4px 6px; text-align:center; vertical-align:middle; }
.timetable th { background:#f5f7fa; }
.sec-col { width:90px; font-weight:600; background:#fafbfc; }
.course-cell {
  background:#67c23a10;
  border:1px solid #67c23a55;
  border-radius:6px;
  margin:0;
  padding:0;
  font-size:12px;
  line-height:1.2;
  width:100%;
  height:100%;
  display:flex;
  flex-direction:column;
  align-items:center;
  justify-content:center;
  box-sizing:border-box;
}
.timetable tbody tr { height: calc((100% - 42px) / 10); }
.course-cell strong { display:block; color:#67c23a; }
.course-cell .minor { color:#666; }
</style>
